import { defineStore } from 'pinia'
import getInitCard from '../components/Editor/card.config'
import group from '../../../components/group.vue'
import { cloneDeep } from 'lodash'
import {
    shallowRef, defineAsyncComponent 
} from 'vue'
import axios from 'axios'
const changeVersionStr = (url, version) => {
    const arr = url.split('/')
    arr[arr.length-2] = version
    return arr.join('/')
}

// 设置最佳缩放级别
export const getBestPos = (width, height) => {
    const maxWidth = innerWidth - 600
    const maxHeight = innerHeight - 120
    const widthScale = maxWidth / width
    const heightScale = maxHeight / height
    let s = Math.min(widthScale, heightScale)
    s > 1.5 && (s = 1.5)
    const left  = 228  - (width - width * s) / 2
    const top = 64 -  (height - height * s) / 2
    return {
        scale: s,
        left,
        top
    }
}
const initWidth = 750
const initHeight = 680
const initPos = getBestPos(initWidth, initHeight)
export const userCardStore = defineStore('cardStore', {
    state: () => ({
        comIndex: '',
        // 视图缩放级别
        scale: 1,
        layout: '0',
        padding: [0,0,0,0],
        name: "预览页面",
        icon: '',
        // 编辑区域
        editor: {
            scale: initPos.scale,
            left: initPos.left,//228,
            top: initPos.top,//64 ,
            right: 330,
            bottom: 0,
            width: initWidth,
            height: initHeight,
            backgroundColor: '#fff',
            scroll: {
                scrollLeft: 0,
                scrollTop: 0
            },
            externals: []
        },
        // 当前组件
        curComponet: null,
        cards: [],
        // 显示控制点的组件
        comControls: [],
        // 不同分辨率的布局设置
        layouts: []
    }),
    actions: {
        refresh(deep = false) {
            if(deep) {
                const t = (cs) => {
                    cs = cs.slice(0)
                    cs.forEach(item => {
                        item.cardJson.initProp.cards && t(item.cardJson.initProp.cards)
                    })
                }
                t(this.cards)
                return
            }
            this.cards = this.cards.slice(0)
        },
        // 设置编辑器的位置和缩放
        setEditorTransform(params = {}, tag) {
            Object.assign( this.editor, params)
            this.editorTransformChange && this.editorTransformChange(tag)
        },
    // 设置当前组件属性
        setCurStyle(config = {}) {
            const curComponet = this.curComponet
            Object.keys(config).forEach((key) => {
                curComponet.style[key] = parseInt(config[key])
            })
        },
        // 添加组件
        addCom(card) {
            !card._id && (card._id = Math.random() + '')
            this.cards.push(card)
            this.curComponet = card
            this.clearControl()
            this.comControl(card, true)
        },
        removeCom(c) {
            const card = c || this.curComponet
            if(!card) return
            const index = this.cards.findIndex(c => c._id === card._id)
            index > -1  && this.cards.splice(index, 1)
        },
        // 设置组件显示控制点
        comControl(card,active) {
            const index = this.comControls.findIndex(item => item === card._id)
            if(active) {
                index === -1 && (this.comControls.push(card._id))
            } else {
                index !== -1 && (this.comControls.splice(index , 1))
            }
        },
        // 清楚所有控制点
        clearControl() {
            this.comControls = []
        },
        // 更新滚动条样式
        updateScrollBar() {
            scrollRef
        },
        // 成组
        addGroup() {
            const cards = this.cards.filter(card => {
                return this.comControls.includes(card._id)
            })
            this.cards = this.cards.filter(card => {
                return !this.comControls.includes(card._id)
            })
            const top =  Math.min(...cards.map(card => card.style.top))
            const left = Math.min(...cards.map(card => card.style.left))
            const bottom =  Math.max(...cards.map(card => card.style.top + card.style.height))
            const right  = Math.max(...cards.map(card => card.style.left + card.style.width))
            cards.forEach(card => {
                card.style.top =  card.style.top -top
                card.style.left =  card.style.left - left
            })
            const groupCard = getInitCard({
                name: '组',
                group: true,
                style: {
                    top,
                    left,
                    width: right - left,
                    height: bottom - top
                },
                component: group,
                cardJson: {
                    initProp: {
                        cards
                    }
                }
            })
            this.addCom(groupCard)
        },
        // 解散组
        removeGroup(card) {
            const index = this.cards.findIndex(item => item._id === card._id)
            this.cards.splice(index, 1)
            const insertIndex = index  === 0 ? 0 : index - 1
            const cards = card.cardJson.initProp.cards
            cards.forEach(c => {
                c.style.top =  c.style.top + card.style.top
                c.style.left =  c.style.left + card.style.left
            })
            this.cards.splice(insertIndex, 0, ...cards)
        },
        // 移动到上一级
        changePrev(card) {
            const index = this.cards.findIndex(item => item._id === card._id)
            if(index === this.cards.length - 1) return
            this.changePos(index, index+1)
        },
        // 移动到下一级
        changeNext(card) {
            const index = this.cards.findIndex(item => item._id === card._id)
            if(index === 0) return
            this.changePos(index, index-1)
     
        },
        // 交互位置
        changePos(pos1, pos2) {
            [this.cards[pos1], this.cards[pos2]] = [this.cards[pos2], this.cards[pos1]]
            this.cards = this.cards.slice()
        },
        // 复制
        copy(card) {
            const newCard = cloneDeep(card)
            // 修改id
            function forCallback(card) {
                card._id = Math.random()
                card.cardJson.initProp.cards && card.cardJson.initProp.cards.forEach(item => {
                    forCallback(item)
                })
            }
            forCallback(newCard)
            this.addCom(newCard)
        },
        // 改变版本
        async changeVersion(version) {
            const {
                url,
                cardJsonUrl,
                panelUrl
            } = this.curComponet
            const newUrl = changeVersionStr(url, version)
            // const newCardJsonUrl = changeVersionStr(cardJsonUrl, version)
            const newPanelUrl = changeVersionStr(panelUrl, version)
            // const res = await axios.get(newCardJsonUrl)
            // const cardJson = res.data
            Object.assign(this.curComponet, {
                component: shallowRef(defineAsyncComponent(() => {
                    return new Promise(async r => {
                        const VueDemo = await import(/* @vite-ignore */`${newUrl}`)
                        console.log('VueDemo', VueDemo)
        
                        r(VueDemo)
                    })
                })) ,
                panelComponent: shallowRef(defineAsyncComponent(() => {
                    return new Promise(async r => {
                        const VueDemo = await import(/* @vite-ignore */`${newPanelUrl}`)
                        console.log('VueDemo', VueDemo)
        
                        r(VueDemo)
                    })
                })) ,
                // cardJson,
                url:newUrl,
                panePlUrl: newPanelUrl,
                // cardJsonUrl: newCardJsonUrl,
            })
        },
        // 获取页面json
        getPageJson() {
            const newCards = cloneDeep(this.cards)
            cardsHandler(newCards)
            return {
                name: this.name,
                layout: this.layout,
                layouts: this.layouts,
                padding: this.padding,
                editor: this.editor,
                cards: newCards
            }
        },
        // 保存页面
        savePage() {
            const json = this.getPageJson()
            sessionStorage.setItem(
                'pageStore',
                JSON.stringify(json)
            )
        }
    }
})

// 目录树
function cardsHandler(cards) {
    for(let i=0,l=cards.length; i<l; i++) {
        const card = cards[i]
        cards[i] = {
            group: card.group,
            style: card.style,
            // interactive: card.interactive,
            class: card.interactive.enterAnimation.isOpacity ? ['fadeIn'] : [],
            enterAnimation: getEnterAnimation(card.interactive.enterAnimation),
            url: card.url,
            _id: card._id,
            cardJson: card.cardJson,
            name_es: card.name_es,
            name: card.name,
            cards: card.cards
        }
        card.cardJson.initProp.cards && cardsHandler(card.cardJson.initProp.cards)

    }
}

// const cardStore = userCardStore()
// 载入动画
function getEnterAnimation(enterAnimation) {
    console.log('getEnterAnimation')
 const {
    type,
    timingFunction,
    direction,
    duration,
    delay,
    isOpacity
 } = enterAnimation
 if(!type && !isOpacity) return {}
 const arr = []
 type && arr.push(direction)
 isOpacity && arr.push('fadeIn')
 return {
    'animation-duration': `${duration}ms`,
    'animation-delay': `${delay}ms`,
    'animation-timing-function': timingFunction,
    'animation-name':arr.join(',')
 }
}